<template>
  <Navbar class="hidden" :navbar-style="{ backgroundColor: '#fff' }">
    <view class="container" :style="[containerStyle]">
      <view class="pl-30rpx"></view>
      <view class="title-container">
        <image
          mode="aspectFill"
          class="w-248rpx h-32rpx"
        />
      </view>
    </view>
  </Navbar>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator'
import Navbar from '@/components/navbar/navbar.vue'
import { appStore, userStore } from '@/store/modules'
import { toPromise, verificationToken } from '@/utils'
import { eventLock } from '@/components/eventLock'
import {
  getMenuButtonBoundingRect,
  getSystemSetting
} from '@/utils/helper/cacheQueryHelper'

@Component({ name: 'TopActionBar', components: { Navbar } })
export default class TopActionBar extends Vue {
  /* 当前选中的租户 */
  currentTenant: AnyObject = {}

  get containerStyle() {
    const { top } = getMenuButtonBoundingRect()
    const { statusBarHeight = 24 } = getSystemSetting()
    return {
      padding: `${top - statusBarHeight}px 0`
    }
  }

  @Watch('currentTenant')
  async onWatchCurrentTenant(newVal: AnyObject) {
    if (eventLock.lockStatus) return
    eventLock.lock()
    const lastTenantId =
      uni.getStorageSync('lastTenantId') || userStore.getLoginTenantId
    if (lastTenantId !== newVal.tenantId) {
      if (verificationToken() < 0) {
        await userStore.Login({ loginType: 2 })
        if (appStore.tenantId !== newVal.tenantId) {
          const { confirm } = await toPromise(uni.showModal, {
            title: '切换提示',
            content: `定位到您在【${newVal.shortName}】服务区域内，是否切换到【${newVal.shortName}】？`,
            confirmText: '切换',
            cancelText: '取消'
          })
          if (confirm) {
            // 带租户切换
            await userStore.Login({ loginType: 3, tenantId: newVal.tenantId })
            uni.setStorageSync('lastTenantId', newVal.tenantId)
          } else {
            uni.setStorageSync('lastTenantId', appStore.tenantId)
          }
        }
      } else {
        try {
          // 如果这个登录报错，吃掉错误，重新登录一遍
          await userStore.Login({
            loginType: userStore.getToken ? 3 : 2,
            tenantId: newVal.tenantId
          })
        } catch (e) {
          await userStore.Login({ loginType: 2, tenantId: newVal.tenantId })
        } finally {
          uni.setStorageSync('lastTenantId', newVal.tenantId)
        }
      }
    }
    // 全局抛出租户变更事件
    uni.$emit('tenant:ok', newVal)
    eventLock.unLock()
  }
}
</script>

<style lang="scss" scoped>
.container {
  @apply w-full h-full flex items-center overflow-hidden;
}

.title-container {
  height: 100%;
  overflow: hidden;
  flex: 1;
  padding: 6rpx 6rpx 6rpx 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
